package cc.taofoo.JUC;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock 重入锁 测试
 * 1. lock()   获得锁，如果已经被占用，则等待
 * 2. lockInterruptibly() 获得锁，响应中断
 * 3. tryLock() 尝试获得锁，成功返回 true ,失败返回 false
 * 4. tryLock(long time,TimeUnit unit)  在给定时间内尝试获得锁
 * 5. unlock()  释放锁
 */


public class ReEnterLock {

    public static void main(String[] args) {
        testIntLock();
    }

    static void testIntLock() {
        IntLock intLock1 = new IntLock(1);
        IntLock intLock2 = new IntLock(2);
        Thread t1 = new Thread(intLock1);
        Thread t2 = new Thread(intLock2);
        t1.start();t2.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt();  // 线程 2 中断，释放锁，解除死锁
    }

}


class IntLock implements Runnable {
    public static ReentrantLock lock1 = new ReentrantLock();
    public static ReentrantLock lock2 = new ReentrantLock();

    int lock;

    public IntLock(int lock) {
        this.lock = lock;
    }


    @Override
    public void run() {
        try {
            if (lock == 1) {
                lock1.lockInterruptibly();  // 线程 1 先拿到 lock1 的锁
                Thread.sleep(200);   // 让 线程2 拿到 lock2 的锁，以产生死锁
                lock2.lockInterruptibly();
            } else {
                lock2.lockInterruptibly();
                Thread.sleep(200);
                lock1.lockInterruptibly();
            }
        } catch (InterruptedException e) {
//            e.printStackTrace();
            System.out.println(Thread.currentThread().getName()+" has been interrupted");
        } finally {
            if (lock1.isHeldByCurrentThread())
                lock1.unlock();
            if (lock2.isHeldByCurrentThread())
                lock2.unlock();
            System.out.println(Thread.currentThread().getName());
        }
    }
}
